package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;

@WebServlet(name = "AdminIndexThreadControllerServlet", urlPatterns = "/Admin/AdminIndexThreadControllerServlet")
public class AdminIndexThreadControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 795859534290467530L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			int boardId = Integer.parseInt(request.getParameter("boardid"));
			int threadId = Integer.parseInt(request.getParameter("threadid"));

			if (user.isBoardAdmin(boardId)) {
				Thread thread = Thread.get(boardId, threadId);
				thread.index();
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/ThreadSelectedControllerServlet?boardid=" + boardId + "&threadid=" + threadId);

		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
